package com.sc.controller;

import com.fasterxml.jackson.annotation.JsonView;
import com.google.common.collect.Lists;
import com.sc.app.security.utils.AppSignUpUtils;
import com.sc.domain.User;

import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;


/**
 * @author sc
 * Created on  2018/1/15
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {


    @Autowired
    private ProviderSignInUtils providerSignInUtils;

    @Autowired
    private AppSignUpUtils appSignUpUtils;

    @PostMapping("/register")
    public void register(@RequestBody User user, HttpServletRequest request){
        //用户注册绑定
         String userId = user.getUsername();
         appSignUpUtils.doPostSignUp(new ServletWebRequest(request),userId);
        log.info("用户注册成功");
    }

    @RequestMapping("/list")
    @JsonView(User.UserQueryView.class)
    public List<User> query(){
        List<User> list = Lists.newArrayList();
        User user = new User(1L, "sc", "pass");
        List<User> list1 = Lists.newArrayList();
        list1.add(user);
        list1.add(user);
        list1.add(user);
        return list1;
    }

    @RequestMapping("/{id:\\d+}")
    @JsonView(User.UserDetailView.class)
    public User getInfo(@PathVariable("id") Long id){
        User user = new User( id,"sc","pass");
        return user;
    }

    @PostMapping
    public User createUser(@ApiParam("用户") @RequestBody @Valid User user, BindingResult result){
        if(result.hasErrors()){
            result.getAllErrors().forEach(error-> System.out.println(error.getDefaultMessage() ));
        }
        System.out.println(user);
        user.setId(1L);
        return user;
    }

    @PutMapping("/{id:\\d+}")
    public User modifyUser(@RequestBody User user){
        System.out.println(user);
        return user;
    }

    @GetMapping("/me")
    public Object getCurrentUser(@AuthenticationPrincipal UserDetails userDetails){
        return userDetails;
    }
}
